package com.cloud.lan.service.aliyun;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.teaopenapi.models.Config;
import com.cloud.lan.aop.RequestClient;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @description:
 * @author: michael
 * @create: 2020-01-08 17:54
 **/
@Slf4j
@Service
public class AliyunService {

    static String accessKeyId, accessKeySecret = null;
    static String bucketName, endpoint, cdnDomain = null;
    static String smsSignName, smsEndpoint, smsLoginTemplateCode = null;
    public String IMAGE_TYPE = ".jpeg";
    public String IMAGE_APP_NAME = "images/";
    public String JSON_APP_NAME = "json/api/";
    @Resource
    public AliyunConfig aliyunConfig;

    /**
     * 阿里云 发送短信 初始化连接
     * @author ErKang
     * @return com.aliyun.dysmsapi20170525.models.SendSmsResponse
     * 2021/12/13 00:42
     */
    public static com.aliyun.dysmsapi20170525.Client createSmsClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = smsEndpoint;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dysmsapi20170525.Client client = createSmsClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers("13813948485")
                .setSignName(smsSignName)
                .setTemplateCode("SMS_228305103")
                .setTemplateParam("{\"code\":\"4545\"}");
        // 复制代码运行请自行打印 API 的返回值
        client.sendSms(sendSmsRequest);
    }

    /**
     * 变量初始化
     * @author ErKang
     * @return void
     * 2021/12/13 00:24
     */
    @PostConstruct
    public void init() {
        log.info("AliyunService 变量初始化 {}", aliyunConfig.toString());
        accessKeyId = aliyunConfig.getAccessKeyId();
        accessKeySecret = aliyunConfig.getAccessKeySecret();
        bucketName = aliyunConfig.getOss().getBucketName();
        endpoint = aliyunConfig.getOss().getEndpoint();
        cdnDomain = aliyunConfig.getOss().getCdnDomain();
        smsSignName = aliyunConfig.getSms().getSignName();
        smsEndpoint = aliyunConfig.getSms().getEndpoint();
        smsLoginTemplateCode = aliyunConfig.getSms().getLoginTemplateCode();
    }

    /**
     * 阿里云 发送短信
     * @author ErKang
     * @return com.aliyun.dysmsapi20170525.models.SendSmsResponse
     * 2021/12/13 00:42
     */
    public synchronized SendSmsResponse smsSend(String mobile, Map<String, Object> contentMap) {
        SendSmsResponse sendSmsResponse = null;
        try {
            com.aliyun.dysmsapi20170525.Client client = createSmsClient();
            JSONObject tempContentJson = JSONObject.fromObject(contentMap);
            //拼接模板中需替换的字符
            String tempContent = tempContentJson.toString();
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(smsSignName)
                    .setTemplateCode(smsLoginTemplateCode)
                    .setTemplateParam(tempContent);
            log.info("请求发送短信接口 {}，{}，{}，{}", mobile, smsSignName, smsLoginTemplateCode, tempContent);
            // 复制代码运行请自行打印 API 的返回值
            sendSmsResponse = client.sendSms(sendSmsRequest);
            log.info("请求发送短信接口返回 sendSmsResponse = {}", JSONObject.fromObject(sendSmsResponse).toString());
        } catch (Exception e) {
            log.error("阿里云发送短信异常>>>：", e);
        }
        return sendSmsResponse;
    }

    /**
     * 通用文件上传
     * @author ErKang
     * @param file
     * @return java.lang.String
     * 2021/12/13 00:11
     */
    public synchronized String upload(MultipartFile file) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String fileUrl = null;
        try {
            InputStream stream = file.getInputStream();
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = IdUtil.simpleUUID() + suffix;
            String folder =
                    IMAGE_APP_NAME + DateUtil.format(new Date(), "yyyy")
                            + "/" + DateUtil.format(new Date(), "MM")
                            + "/" + DateUtil.format(new Date(),
                            "dd") + "/";
            fileUrl = folder + fileName;
            log.info("感谢您使用阿里云对象存储服务>>>已上传文件：{}", String.format("%s/%s", cdnDomain, fileUrl));
            ossClient.putObject(bucketName, fileUrl, stream);
        } catch (OSSException e) {
            log.error("阿里云文件上传异常>>>：", e);
        } catch (com.aliyun.oss.ClientException e) {
            log.info("阿里云文件上传异常>>>：", e);
        } catch (IOException e) {
            log.info("阿里云文件上传异常>>>：", e);
        } finally {
            ossClient.shutdown();
        }
        return String.format("%s/%s", cdnDomain, fileUrl);
    }

    /**
     * 上传文件内容
     * @author ErKang
     * @return java.lang.String
     * 2021/12/13 01:02
     */
    @RequestClient
    public synchronized String uploadJson(String fileName, String content) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String fileUrl = JSON_APP_NAME + fileName + ".json";
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileUrl,
                    new ByteArrayInputStream(content.getBytes()));
            log.info("感谢您使用阿里云对象存储服务>>>已上传文件：{}", String.format("%s/%s", cdnDomain, fileUrl));
            ossClient.putObject(putObjectRequest);
        } catch (OSSException e) {
            log.error("阿里云文件上传异常>>>：", e);
        } catch (com.aliyun.oss.ClientException e) {
            log.info("阿里云文件上传异常>>>：", e);
        } finally {
            ossClient.shutdown();
        }
        return String.format("%s/%s", cdnDomain, fileUrl);
    }

    public synchronized void download(String fileName, File outFile) {
        String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAIYXwwS3RwlvZp";
        String accessKeySecret = "YDidWUnpARQSIXrCyK1WIHApKa9byH";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        // <yourObjectName>表示上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ossClient.getObject(new GetObjectRequest("freebrio", fileName), outFile);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

}
